package crud

import (
	"fmt"
	"os"
	"strings"

	"cms/system/helper"
)

var addTmpl = `<?php
namespace {{.__NAMESPACE__}};

use think\Validate;

class {{.__CLASS__}} extends Validate
{
    //数组顺序就是检测的顺序
    protected $rule = [
		{{.__RULE__}}
    ];

    //定义内置方法检验失败后返回的字符
    protected $message = [
		{{.__MSG__}}
    ];
}
`

var editTmpl = `<?php
namespace {{.__NAMESPACE__}};

use think\Validate;

class {{.__CLASS__}} extends Validate
{
    //数组顺序就是检测的顺序
    protected $rule = [
        'id'               => 'require|number',
		{{.__RULE__}}
    ];

    //定义内置方法检验失败后返回的字符
    protected $message = [
        'id.require'         => '缺少id',
		'id.number'         => 'id必须为整数',
		{{.__MSG__}}
    ];
}
`

// 生成验证器
func (g *cGlobal) MakeValidate() error {
	err := g.addValidate()
	if err != nil {
		return err
	}

	err = g.editValidate()
	if err != nil {
		return err
	}

	return nil
}

// 生成验证器
func (g *cGlobal) addValidate() error {
	return g.doValidate("add", addTmpl)
}

// 生成验证器
func (g *cGlobal) editValidate() error {
	return g.doValidate("edit", editTmpl)
}

func (g *cGlobal) doValidate(s string, tmpl string) error {
	err := os.MkdirAll(g.AppPath.ValidatePath, os.ModePerm)
	if err != nil {
		return err
	}

	tbInfo := g.TableSchema
	sRule := make([]string, 0)
	sMsg := make([]string, 0)

	if g.Field != nil {
		for key, val := range g.Field {
			if key == "id" || key == "create_time" || key == "update_time" || key == "delete_time" {
				continue
			}

			if val["require"] == "true" {
				label := val["name"]
				ruleItem := "require|length:1, 10"
				sKey := key + ".require"
				sVal := label + "不能为空"
				tmp := fmt.Sprintf("\t\t'%v' => '%v'", key, ruleItem)

				sRule = append(sRule, tmp)

				sMsg = append(sMsg, fmt.Sprintf("\t\t'%v' => '%v'", sKey, sVal))
				sMsg = append(sMsg, fmt.Sprintf("\t\t'%v' => '%v'", key+".length", label+"长度为1-10"))
			}

		}
	} else {
		for _, column := range tbInfo {
			if column["column"] == "id" || column["column"] == "create_time" || column["column"] == "update_time" || column["column"] == "delete_time" {
				continue
			}

			comment := column["comment"]
			label := comment
			if comment != "" {
				if idx := strings.Index(comment, "("); idx > 0 {
					label = comment[:idx]
					rules := comment[idx+1:]
					rules = strings.ReplaceAll(rules, "(", "")
					rules = strings.ReplaceAll(rules, ")", "")

					// 必选
					if strings.Index(comment, "require") > 0 {
						ruleItem := "require"
						sKey := column["column"] + ".require"
						sVal := label + "不能为空"
						if column["ctype"] == "varchar" {
							ruleItem += "|length:1," + column["length"]
						}
						tmp := fmt.Sprintf("\t\t'%v' => '%v'", column["column"], ruleItem)

						sRule = append(sRule, tmp)
						sMsg = append(sMsg, fmt.Sprintf("\t\t'%v' => '%v'", sKey, sVal))
						if column["ctype"] == "varchar" {
							sMsg = append(sMsg, fmt.Sprintf("\t\t'%v' => '%v'", column["column"]+".length", label+"长度为2-"+column["length"]))
						}
					}
				}
			}
		}
	}

	m := map[string]string{
		"__NAMESPACE__": g.NameSpace.Validate,
		"__CLASS__":     helper.UcFirst(s),
		"__RULE__":      strings.Join(sRule, ", \n"),
		"__MSG__":       strings.Join(sMsg, ", \n"),
	}

	fileName := ""
	if s == "add" {
		fileName = g.AppFiles.ValidateAdd
	} else {
		fileName = g.AppFiles.ValidateEdit
	}

	err = TemplateExec(fileName, tmpl, m)
	if err != nil {
		return err
	}

	return nil
}
